import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

// **********************  登录主体路由组件  **********************
import Login from '../pages/Login.vue'
import Home from '../pages/Home.vue'
// ********************  内容组件路由组件  * *******************
import Welcome from '../Welcome/Welcome.vue'
import User from '../pages/User.vue'
import Roles from '../pages/Roles.vue'
import Rights from '../pages/Rights.vue'
import Goods from '../pages/Goods.vue'
import Params from '../pages/Params.vue'
import Categories from '../pages/Categories.vue'
import Orders from '../pages/Orders.vue'
import Reports from '../pages/Reports.vue'
import Add from '../pages/Add/Add.vue'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'login', component: Login },
  {
    path: '/home',
    name: 'home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', name: 'welcome', component: Welcome },
      { path: '/users', name: 'user', component: User },
      { path: '/roles', name: 'roles', component: Roles },
      { path: '/rights', name: 'rights', component: Rights },
      { path: '/goods', name: 'goods', component: Goods },
      { path: '/goods/add', name: 'add', component: Add },
      { path: '/params', name: 'params', component: Params },
      { path: '/categories', name: 'categories', component: Categories },
      { path: '/orders', name: 'orders', component: Orders },
      { path: '/reports', name: 'reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})

// **************全局的导航守卫******************
router.beforeEach((to, from, next) => {
  // console.log('to', to.path)

  let token = window.sessionStorage.getItem('token')

  // 把需要拦截未登录访问的权限页面 全部都加到数组里面
  let autlUrlArr = ['/home']
  // 如果访问的是 /user  => 继续判断
  // if(to.path === '/user' || to.path)
  // if (autlUrlArr.indexOf(to.path) > -1) {
  if (autlUrlArr.includes(to.path)) {
    // 如果登录了 可以访问
    if (token) {
      next()
    } else {
      // 如果没有登录 跳转到登录页面
      next('/login')
    }
  } else {
    // 如果访问的是 /login  /register  => 永远可以
    next()
  }
})

// ********************* 去除路由重复的报错提示 ********************
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
